<template>
  <div id="resourcePage">
    <div style="display: flex; justify-content: space-between">
      <!-- 搜索栏 -->
      <a-form layout="inline" :model="searchParam" @finish="doSearch">
        <a-form-item label="资源名称">
          <a-input
            v-model:value="searchParam.resourceName"
            placeholder="请输入资源名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="资源类型">
          <a-input
            v-model:value="searchParam.resourceType"
            placeholder="请输入资源类型"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="关键词">
          <a-input v-model:value="searchParam.keyword" placeholder="请输入关键词" allow-clear />
        </a-form-item>
        <a-form-item label="上传者">
          <a-input
            v-model:value="searchParam.uploaderName"
            placeholder="请输入上传者"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit"> 搜索 </a-button>
        </a-form-item>
      </a-form>
      <a-button type="primary" size="large" @click="showAddModel">新增资源</a-button>
    </div>
    <div style="margin-bottom: 32px"></div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH-mm-ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="default" @click="downloadFile(record.id, record.resourceUrl)">
              <template #icon>
                <DownloadOutlined />
              </template>
              下载
            </a-button>
            <a-button type="primary" @click="showUpdateModel(record.id)">修改</a-button>
            <a-button type="primary" danger @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="addModel" title="添加资源" @ok="doAdd">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataAdd"
        name="addResource"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="资源名称" name="resourceName">
          <a-input v-model:value="formDataAdd.resourceName" />
        </a-form-item>
        <a-form-item label="资源类型" name="resourceType">
          <a-input v-model:value="formDataAdd.resourceType" />
        </a-form-item>
        <a-form-item label="资源文件" name="resourceUrl">
          <a-upload
            v-model:file-list="fileList"
            :maxCount="1"
            :beforeUpload="beforeUpload"
            :customRequest="handleUpload"
          >
            <a-button>
              <UploadOutlined></UploadOutlined>
              上传文件
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item label="资源描述" name="description">
          <a-textarea v-model:value="formDataAdd.description" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="updateModel" title="更新资源信息" @ok="doUpdate">
      <div style="height: 16px"></div>
      <a-form
        :model="formDataUpdate"
        name="updateResource"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="资源名称" name="resourceName">
          <a-input v-model:value="formDataUpdate.resourceName" />
        </a-form-item>
        <a-form-item label="资源类型" name="resourceType">
          <a-input v-model:value="formDataUpdate.resourceType" />
        </a-form-item>
        <a-form-item label="资源文件" name="resourceUrl">
          <a-upload
            v-model:file-list="fileList"
            :maxCount="1"
            :beforeUpload="beforeUpload"
            :customRequest="handleUpload"
          >
            <a-button>
              <UploadOutlined></UploadOutlined>
              上传文件
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item label="资源描述" name="description">
          <a-textarea v-model:value="formDataUpdate.description" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import { message, type UploadProps } from 'ant-design-vue'
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import {
  addResourceUsingPost,
  deleteResourceUsingPost,
  getResourceByIdUsingGet,
  listResourceByPageUsingPost, updateDownloadCountUsingPost,
  updateResourceUsingPost
} from '@/api/resourceController.ts'
import { uploadFileUsingPost } from '@/api/fileUploadController.ts'

const addModel = ref<boolean>(false)
const updateModel = ref<boolean>(false)

const columns = [
  {
    title: '资源名称',
    dataIndex: 'resourceName',
  },
  {
    title: '资源类型',
    dataIndex: 'resourceType',
  },
  {
    title: '资源描述',
    dataIndex: 'description',
  },
  {
    title: '下载次数',
    dataIndex: 'downloadCount',
  },
  {
    title: '上传者',
    dataIndex: 'uploaderName',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.Resource[]>([])
const total = ref(0)

// 搜索条件
const searchParam = reactive<API.ResourceQueryRequest>({
  current: 1,
  pageSize: 10,
  resourceName: '',
  resourceType: '',
  keyword: '',
  uploaderName: '',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParam.current,
    pageSize: searchParam.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`,
  }
})

const doTableChange = (page: any) => {
  searchParam.current = page.current
  searchParam.pageSize = page.pageSize
  fetchData()
}

// 获取数据
const fetchData = async () => {
  const res = await listResourceByPageUsingPost({
    ...searchParam,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败' + res.data.message)
  }
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
})

const doSearch = () => {
  // 重置页码
  searchParam.current = 1
  fetchData()
}

const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  const res = await deleteResourceUsingPost({ id: id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

const formDataAdd = reactive<API.ResourceAddRequest>({
  resourceName: '',
  resourceType: '',
  resourceUrl: '',
  description: '',
})
const formDataUpdate = ref<API.ResourceUpdateRequest>({
  resourceName: '',
  resourceType: '',
  resourceUrl: '',
  description: '',
})

const doUpdate = async () => {
  const res = await updateResourceUsingPost({
    ...formDataUpdate.value,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('更新成功')
    fetchData()
    updateModel.value = false
  } else {
    message.error('更新失败, ' + res.data.message)
  }
}

const doAdd = async () => {
  const res = await addResourceUsingPost({
    ...formDataAdd,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('添加成功')
    fetchData()
    addModel.value = false
  } else {
    message.error('添加失败, ' + res.data.message)
  }
}

const fileList = ref<UploadProps['fileList']>([])

const showAddModel = async () => {
  formDataAdd.resourceName = ''
  formDataAdd.resourceType = ''
  formDataAdd.resourceUrl = ''
  formDataAdd.description = ''
  fileList.value = []
  addModel.value = true
}

const showUpdateModel = async (id: number) => {
  const res = await getResourceByIdUsingGet({ id })
  if (res.data.code === 0 && res.data.data !== null) {
    formDataUpdate.value = {
      ...res.data.data,
    }
    fileList.value = [
      {
        uid: '1',
        name: formDataUpdate.value.resourceName ?? '',
        status: 'done',
        url: formDataUpdate.value.resourceUrl,
      },
    ]
  } else {
    message.error('获取数据失败, ' + res.data.message)
  }
  updateModel.value = true
}

/**
 * 上传文件
 * @param file
 */
const handleUpload = async ({ file }: any) => {
  try {
    const res = await uploadFileUsingPost({}, file)
    if (res.data.code === 0 && res.data.data) {
      message.success('文件上传成功')
      formDataAdd.resourceUrl = res.data.data
      formDataUpdate.value.resourceUrl = res.data.data
      if (fileList.value) {
        fileList.value[0].status = 'done'
      }
    } else {
      message.error('文件上传失败，' + res.data.message)
      if (fileList.value) {
        fileList.value[0].status = 'error'
      }
    }
  } catch (error) {
    console.log('文件上传失败，' + error)
    message.error('文件上传失败，' + error)
  }
}

/**
 * 上传前的校验
 * @param file
 */
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 校验文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('不能上传超过 10M 的图片')
  }
  return isLt10M
}

const downloadFile = async (id: number, fileUrl: string) => {
  const res = await updateDownloadCountUsingPost({
    id: id,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('下载成功')
  } else {
    message.error('下载失败, ' + res.data.message)
  }
  window.open(fileUrl)
}
</script>

<style scoped></style>
